from flask import Flask, jsonify
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
from flask_jwt_extended import JWTManager
from dotenv import load_dotenv
import os

# 加载环境变量
load_dotenv()

# 初始化应用
app = Flask(__name__)
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY')
app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv('DATABASE_URL')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# 配置SQLAlchemy选项，适用于MySQL
app.config['SQLALCHEMY_ENGINE_OPTIONS'] = {
    'echo': True,  # 打印SQL语句，方便调试
    'pool_recycle': 3600,  # 连接回收时间，避免数据库断开连接
    'pool_pre_ping': True  # 在使用连接前检查连接是否有效
}
app.config['JWT_SECRET_KEY'] = os.getenv('SECRET_KEY')
# 添加JWT配置
app.config['JWT_TOKEN_LOCATION'] = ['headers']
app.config['JWT_HEADER_NAME'] = 'Authorization'
app.config['JWT_HEADER_TYPE'] = 'Bearer'
app.config['JWT_IDENTITY_CLAIM'] = 'sub'  # 确保subject声明正确

# 详细的CORS配置
CORS(app, resources={
    r"/api/*": {
        "origins": ["http://localhost:3000", "http://127.0.0.1:3000"],  # 前端开发服务器地址
        "methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
        "allow_headers": ["Content-Type", "Authorization"],
        "supports_credentials": True
    }
})

# 初始化扩展
db = SQLAlchemy(app)
jwt = JWTManager(app)

# JWT相关回调
@jwt.user_identity_loader
def user_identity_lookup(identity):
    # 确保identity始终是字符串
    return str(identity)

@jwt.user_lookup_loader
def user_lookup_callback(_jwt_header, jwt_data):
    from app.models.user_model import User
    identity = jwt_data["sub"]
    return User.query.filter_by(id=int(identity)).one_or_none()

# 错误处理
@app.errorhandler(Exception)
def handle_error(error):
    print(f"Error: {str(error)}")  # 添加日志
    return jsonify({"error": str(error)}), 500

# 导入路由
from app.routes.auth_routes import auth_bp
from app.routes.chat_routes import chat_bp
from app.routes.data_routes import data_bp

# 注册路由
app.register_blueprint(auth_bp, url_prefix='')
app.register_blueprint(chat_bp, url_prefix='')
app.register_blueprint(data_bp, url_prefix='')

# 导入模型
from app.models import user_model, message_model, data_model

# 创建数据库表
with app.app_context():
    db.create_all() 